package com.yugao.fintech.antelope.pay.payment.listener;

import com.rabbitmq.client.Channel;
import com.yugao.fintech.antelope.pay.common.constants.MqCons;
import com.yugao.fintech.antelope.pay.common.model.mq.ResetIsvMchAppInfoConfigMQ;
import com.yugao.fintech.antelope.pay.payment.service.ConfigContextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Slf4j
@Lazy(value = false)
@Component
@RabbitListener(bindings = {
        @QueueBinding(
//                value = @Queue(value = ResetIsvMchAppInfoConfigMQ.QUEUE, durable = "true"),
                value = @Queue(durable = "true"), // 切记: 此处无需设置队列名称，否在得话，多个消费者只有一个消费者能消费数据。其它消费者无法消费数据
                exchange = @Exchange(value = MqCons.EVENT_EXCHANGE, type = ExchangeTypes.FANOUT))
})
public class ResetIsvMchAppInfoListener {

    @Autowired
    private ConfigContextService configContextService;

    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) {
        try {
            ResetIsvMchAppInfoConfigMQ.MsgPayload payload = ResetIsvMchAppInfoConfigMQ.parse(msg, ResetIsvMchAppInfoConfigMQ.MsgPayload.class);
            if (payload.getResetType() == ResetIsvMchAppInfoConfigMQ.RESET_TYPE_ISV_INFO) {
                this.updateIsvInfo(payload.getIsvNo());
            } else if (payload.getResetType() == ResetIsvMchAppInfoConfigMQ.RESET_TYPE_MCH_INFO) {
                this.updateMchInfo(payload.getMchNo());
            } else if (payload.getResetType() == ResetIsvMchAppInfoConfigMQ.RESET_TYPE_MCH_APP) {
                this.updateMchApp(payload.getMchNo(), payload.getMchAppId());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 接收 [商户配置信息] 的消息
     */
    private void updateIsvInfo(String mchNo) {
        log.info("成功接收 [商户配置信息] 的消息, msg={}", mchNo);
        configContextService.initMchInfoConfigContext(mchNo);
        log.info(" [商户配置信息] 已重置");
    }

    /**
     * 接收 [商户应用支付参数配置信息] 的消息
     */
    private void updateMchApp(String mchNo, String appId) {
        log.info("成功接收 [商户应用支付参数配置信息] 的消息, mchNo={}, appId={}", mchNo, appId);
        configContextService.initMchAppConfigContext(mchNo, appId);
        log.info(" [商户应用支付参数配置信息] 已重置");
    }

    /**
     * 重置ISV信息
     */
    private void updateMchInfo(String isvNo) {
        log.info("成功接收 [ISV信息] 重置, msg={}", isvNo);
        configContextService.initIsvConfigContext(isvNo);
        log.info("[ISV信息] 已重置");
    }
}
